<?php

namespace App\Common;

use AlibabaCloud\SDK\Imageenhan\V20190930\Imageenhan;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Imageenhan\V20190930\Models\GenerateCartoonizedImageAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;

class GenerateCartoonizedImageAdvance
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Imageenhan Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        //初始化配置对象Darabonba\OpenApi\Models\Config。
        //Config对象存放accessKeyId、accessKeySecret、endpoint等配置
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "imageenhan.cn-shanghai.aliyuncs.com";
        return new Imageenhan($config);
    }

    /**
     * @param $args
     * @return false|mixed|void
     */
    public static function main($args)
    {
        // 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html。
        // 如果您使用的是RAM用户的AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
        $accessKeyId = 'LTAI5tEW76t7hqHbyADZeQW2';
        $accessKeySecret = '6uTK0HlMdikxy7o9hNkckCEwnOjX92';
        $client = self::createClient($accessKeyId, $accessKeySecret);
        // 场景一，使用本地文件
        //$file = fopen('/tmp/GenerateCartoonizedImage.jpg', 'rb');
        //$stream = new Stream($file);
        // 场景二，使用任意可访问的url
        $file = fopen($args['img'], 'rb');
        $stream = new Stream($file);
        $generateCartoonizedImageAdvanceRequest = new GenerateCartoonizedImageAdvanceRequest([
            "imageUrlObject" => $stream,
            "imageType" => "girl",
            "index" => $args['type']
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->generateCartoonizedImageAdvance($generateCartoonizedImageAdvanceRequest, $runtime);
            # 获取整体结果
            $result = json_decode(Utils::toJSONString($resp->body), true);

            if (isset($result['RequestId']) && $result['RequestId']) {
                return $result['RequestId'];
            }
        } catch (Exception $exception) {
            # 获取整体报错信息
            return false;
        }
    }
}
